<template>
  <el-dialog
    v-model="state.open"
    :title="state.title"
    :width="447"
    :before-close="cancel"
  >
    <el-form :model="state.formItem" :rules="state.rules" ref="usersRoleRef">
      <el-form-item label="当前的用户">
        {{ state.formItem.us }}
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="state.formItem.roleId" >
          <el-option
            v-for="item in state.roleList"
            :key="item['roleId']"
            :label="item['roleName']"
            :value="item['roleId']"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center;">
        <el-button @click="cancel">关闭</el-button>
        <el-button type="primary" :loading="state.loading" @click="ok">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { defineComponent, reactive, toRefs, ref, unref, onMounted } from 'vue'
import { usersUpdateRole } from '@/api/user'
import { rolesPage } from '@/api/role'
import { ElMessage } from 'element-plus'
export default defineComponent({
  name: 'usersRole',
  emits:['reload'],
  setup(prop, context) {
    const usersRoleRef = ref()
    // reactive定义多个数据的响应式
    const state = reactive({
      open: false,
      title: "分配角色",
      loading: false,
      formItem: {
        us: '',
        id: '',
        roleId: ''
      },
      rules: {
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }]
      },
      roleList: [
        { roleId: 1, roleName: "测试1" }
      ]
    })

    const init = (params) => {
      state.formItem = {
        us: params.us,
        id: params.id,
        roleId: params.roleId,
      }
      state.open = true
    }

    const cancel = () => {
      unref(usersRoleRef).resetFields()
      state.open = false
    }

    const ok = () => {
      unref(usersRoleRef).validate((valid) => {
        if (!valid) return
        usersUpdateRole(state.formItem)
          .then((res) => {
            if (res.data.code === 200) {
              ElMessage.success('角色分配成功')
              state.open = false
              context.emit('reload')
            }
          })
      })
    }

    const getRolesList = () => {
      rolesPage()
        .then((res) => {
          if (res.data.code === 200) {
            const data = res.data
            state.roleList = data.data
          }
        })
    }

    onMounted(() => {
      getRolesList()
    })

    return {
      state,
      cancel,
      ok,
      usersRoleRef,
      init
    }
  }
})
</script>
